package com.xmtlxx.web.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.xmtlxx.common.annotation.Log;
import com.xmtlxx.common.annotation.RepeatSubmit;
import com.xmtlxx.common.core.controller.BaseController;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.R;
import com.xmtlxx.common.core.domain.entity.SysProcess;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.core.validate.AddGroup;
import com.xmtlxx.common.core.validate.EditGroup;
import com.xmtlxx.common.core.validate.QueryGroup;
import com.xmtlxx.common.enums.BusinessType;
import com.xmtlxx.common.enums.ModelBussType;
import com.xmtlxx.common.enums.UserType;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.common.utils.poi.ExcelUtil;
import com.xmtlxx.system.domain.bo.SysModelBo;
import com.xmtlxx.system.domain.bo.SysOssBo;
import com.xmtlxx.system.domain.bo.SysProcessBo;
import com.xmtlxx.system.domain.bo.SysWorklogBo;
import com.xmtlxx.system.domain.vo.*;
import com.xmtlxx.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * 业务模型Controller
 *
 * @author xmtlxx
 * @date 2022-04-24
 */
@Validated
@Api(value = "业务模型控制器", tags = {"业务模型管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/sysModel")
public class SysModelController extends BaseController {

    private final ISysModelService iSysModelService;

    private final ISysProcessService processService;

    private final ISysWorklogService worklogService;

    private final ISysNodeService nodeService;

    private final ISysOssService ossService;

    /**
     * 返回一个初始化的对象到前端，方便进行动态渲染
     */
    @ApiOperation("用于返回一个初始化对象")
    @PostMapping("/initBean")
    R<SysModelVo> initBean(){
        SysModelVo vo = new SysModelVo();
        //可以对数据进行初始化
        return R.ok(vo);
    }

    /**
     * 查询业务模型列表
     */
    @ApiOperation("查询业务模型列表")
    @SaCheckPermission("datas:query:model")
    @GetMapping("/list")
    public TableDataInfo<SysModelVo> list(@Validated(QueryGroup.class) SysModelBo bo, PageQuery pageQuery) {
        if(!LoginHelper.isAdmin()){
            bo.setTenantId(LoginHelper.getTenantId());
        }
        return iSysModelService.queryPageList(bo, pageQuery);
    }

    /**
     * 获取业务模型列表
     */
    @ApiOperation("获取业务模型列表")
    @SaCheckPermission("datas:query:model")
    @GetMapping("/queryModel")
    public R<List<SysModelVo>> queryModel(@Validated(QueryGroup.class) SysModelBo bo) {
        if(!LoginHelper.isAdmin()){
            bo.setTenantId(LoginHelper.getTenantId());
        }
        bo.setDelFlag("0");
        return R.ok(iSysModelService.queryList(bo));
    }

    /**
     * 导出业务模型列表
     */
    @ApiOperation("导出业务模型列表")
    @SaCheckPermission("system:sysModel:export")
    @Log(title = "业务模型", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@Validated SysModelBo bo, HttpServletResponse response) {
        if(!LoginHelper.isAdmin()){
            bo.setTenantId(LoginHelper.getTenantId());
        }
        List<SysModelVo> list = iSysModelService.queryList(bo);
        ExcelUtil.exportExcel(list, "业务模型", SysModelVo.class, response);
    }

    /**
     * 获取业务模型详细信息
     */
    @ApiOperation("获取业务模型详细信息")
    @SaCheckPermission("datas:query:model")
    @GetMapping("/{modelid}")
    public R<SysModelVo> getInfo(@ApiParam("主键")
                                     @NotNull(message = "主键不能为空")
                                     @PathVariable("modelid") String modelid) {
        return R.ok(iSysModelService.queryById(modelid));
    }

    /**
     * 新增业务模型
     */
    @ApiOperation("新增业务模型")
    @SaCheckPermission("system:sysModel:add")
    @Log(title = "业务模型", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SysModelVo vo) {
        SysModelBo bo = new SysModelBo();
        BeanUtil.copyProperties(vo,bo);
        if(!LoginHelper.isAdmin()){
            bo.setTenantId(LoginHelper.getTenantId());
        }
        return toAjax(iSysModelService.insertByBo(bo,vo.getItems()) ? 1 : 0);
    }

    /**
     * 修改业务模型
     */
    @ApiOperation("修改业务模型")
    @SaCheckPermission("system:sysModel:edit")
    @Log(title = "业务模型", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysModelVo vo) {
        SysModelBo bo = new SysModelBo();
        BeanUtil.copyProperties(vo,bo);
        return toAjax(iSysModelService.updateByBo(bo,vo.getItems()) ? 1 : 0);
    }

    /**
     * 删除业务模型
     */
    @ApiOperation("删除业务模型")
    @SaCheckPermission("system:sysModel:remove")
    @Log(title = "业务模型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{modelids}")
    public R<Void> remove(@ApiParam("主键串")
                          @NotEmpty(message = "主键不能为空")
                          @PathVariable String[] modelids) {
        return toAjax(iSysModelService.deleteWithValidByIds(Arrays.asList(modelids), true) ? 1 : 0);
    }

    /**
     * 业务流程启动
     */
    @ApiOperation("业务流程启动")
    @Log(title = "业务流程启动", businessType = BusinessType.UPDATE)
    @PostMapping("/startModelWorkflow")
    public R<Void> startModelWorkflow(@RequestBody ModelParams params) {
        return toAjax(iSysModelService.startModelWorkflow(params.getBussType(),params.getBussId(),params.getMid()) ? 1 : 0);
    }

    /**
     * 业务流程启动
     */
    @ApiOperation("业务流程终止")
    @Log(title = "业务流程终止", businessType = BusinessType.UPDATE)
    @PostMapping("/endModelWorkflow")
    public R<Void> endModelWorkflow(@RequestBody ModelParams params) {
        return toAjax(iSysModelService.endModelWorkflow(params.getBussType(),params.getBussId(),params.getMid()) ? 1 : 0);
    }

    /**
     * 业务流程启动
     */
    @ApiOperation("业务流程完成")
    @Log(title = "业务流程完成", businessType = BusinessType.UPDATE)
    @PostMapping("/finishModelWorkflow")
    public R<Void> finishModelWorkflow(@RequestBody ModelParams params) {
        return toAjax(iSysModelService.finishModelWorkflow(params.getBussType(),params.getBussId(),params.getMid()) ? 1 : 0);
    }

    /**
     * 业务处理
     */
    @ApiOperation("业务处理")
    @Log(title = "业务处理", businessType = BusinessType.UPDATE)
    @PostMapping("/nodeDeal")
    public R<Void> nodeDeal(@RequestBody SysWorklogVo worklog) {
       SysProcess process = iSysModelService.nodeDeal(worklog);
       if(process != null){
           SysNodeVo node = nodeService.queryById(process.getNid());
           if(node != null && StringUtils.isNotBlank(node.getEflag()) && node.getEflag().equals("Y")){
               switch (worklog.getBusstype()){
                   case "0":

                       break;
                   case "1":

                       break;
                   case "2":

                       break;
               }
           }
       }
       return toAjax(1);
    }

    /**
     * 业务流程信息
     */
    @ApiOperation("业务流程信息")
    @Log(title = "业务流程信息", businessType = BusinessType.OTHER)
    @GetMapping("/process")
    public R<Map<String,Object>> process(String bussid) {
        Map<String,Object> data = new HashMap<>();
        SysProcessBo bo = new SysProcessBo();
        bo.setBussid(bussid);
        Long seq = 0l;
        List<SysProcessVo> result = processService.queryList(bo);
        seq = Long.valueOf(result.size()+"");
        for(SysProcessVo vo : result){
            SysWorklogBo logParams = new SysWorklogBo();
            logParams.setPid(vo.getPid());
            List<SysWorklogVo> logs = worklogService.queryList(logParams);
            vo.setLogs(logs);
            if(vo.getStatus().equals("1")){
                seq = vo.getSeq();
            }
        }
        data.put("result",result);
        data.put("seq",seq);
        return R.ok(data);
    }

    /**
     * 业务流程信息
     */
    @ApiOperation("业务流程信息")
    @Log(title = "业务流程信息", businessType = BusinessType.OTHER)
    @GetMapping("/worklog")
    public R<List<SysWorklogVo>> worklog(String bussid) {
        SysWorklogBo logParams = new SysWorklogBo();
        logParams.setObjid(bussid);
//        logParams.setStatus("1");
        return R.ok(worklogService.queryList(logParams));
    }

    /**
     * 待办流程信息
     */
    @ApiOperation("待办流程信息")
    @Log(title = "待办流程信息", businessType = BusinessType.OTHER)
    @GetMapping("/need")
    public R<SysWorklogVo> need(String bussid) {
        SysWorklogBo logParams = new SysWorklogBo();
        logParams.setObjid(bussid);
        logParams.setUserId(LoginHelper.getUserId());
        logParams.setDeptId(LoginHelper.getDeptId());
        SysWorklogVo vo =  worklogService.getNeedWorklog(logParams);
        return R.ok(vo);
    }

    /**
     * 业务流程信息
     */
    @ApiOperation("业务人员信息")
    @Log(title = "业务人员信息", businessType = BusinessType.OTHER)
    @GetMapping("/operatores")
    public R<List<SysWorklogVo>> operatores(String bussid) {
        SysWorklogBo logParams = new SysWorklogBo();
        logParams.setObjid(bussid);
        logParams.setStatus("1");
        return R.ok(worklogService.queryWorkOperatores(logParams));
    }

    /**
     * 业务日志流程信息
     */
    @ApiOperation("业务日志流程信息")
    @Log(title = "业务日志流程信息", businessType = BusinessType.OTHER)
    @GetMapping("/processlog")
    public R<Map<String,Object>> processlog(String logid) {
        Map<String,Object> data = new HashMap<>();
        SysWorklogVo worklog = worklogService.queryById(logid);
        String bussid = worklog.getObjid();
        //获取BussObject信息
        ModelBussType bussType = ModelBussType.getBussTypeByCode(worklog.getBusstype());
        if(bussType.equals(ModelBussType.EVALU)){

        }else{

        }
        data.put("bussType",worklog.getBusstype());
        //获取Process
        SysProcessBo bo = new SysProcessBo();
        bo.setBussid(bussid);
        Long seq = 0l;
        List<SysProcessVo> result = processService.queryList(bo);
        for(SysProcessVo vo : result){
            SysWorklogBo logParams = new SysWorklogBo();
            logParams.setPid(vo.getPid());
            List<SysWorklogVo> logs = worklogService.queryList(logParams);
            vo.setLogs(logs);
            if(vo.getStatus().equals("1")){
                seq = vo.getSeq();
            }
        }
        data.put("result",result);
        data.put("seq",seq);
        //获取待办
        SysWorklogBo logParams = new SysWorklogBo();
        logParams.setObjid(bussid);
        logParams.setUserId(LoginHelper.getUserId());
        logParams.setDeptId(LoginHelper.getDeptId());
        data.put("need",worklogService.getNeedWorklog(logParams));
        //获取日志列表
        logParams = new SysWorklogBo();
        logParams.setObjid(bussid);
        data.put("logs",worklogService.queryList(logParams));
        //获取图片
        SysOssBo ossBo = new SysOssBo();
        ossBo.setObjid(bussid);
        data.put("pics",ossService.selectSysOssList(ossBo));
        return R.ok(data);
    }


    /**
     * 待办事项列表
     */
    @ApiOperation("待办事项列表")
    @Log(title = "待办事项列表", businessType = BusinessType.OTHER)
    @GetMapping("/undeals")
    public TableDataInfo<SysWorklogVo> undeals(PageQuery pageQuery) {
        SysWorklogBo logParams = new SysWorklogBo();
        if(LoginHelper.getUserType().equals(UserType.SYS_USER)){
            logParams.setUserId(LoginHelper.getUserId());
            logParams.setDeptId(LoginHelper.getDeptId());
        }else if(LoginHelper.getUserType().equals(UserType.PATROL)){
            logParams.setUserId(LoginHelper.getUserId());
        }
        logParams.setStatus("0");
//        List<SysWorklogVo> logs = worklogService.queryList(logParams);
        return worklogService.queryPageList(logParams,pageQuery);
    }

    /**
     * APP首页进度列表
     */
    @ApiOperation("APP首页进度列表")
    @Log(title = "APP首页进度列表", businessType = BusinessType.OTHER)
    @GetMapping("/appIndexProcess")
    public R<List<Map<String,Object>>> appIndexProcess() {
        List<Map<String,Object>> data = new ArrayList<>();
        SysProcessBo bo = new SysProcessBo();
        bo.setStatus("1");
        List<SysProcessVo> result = processService.queryList(bo);
        if(result != null && result.size() > 0){
            result.forEach(item ->{
                Map<String,Object> map = new HashMap<>();
                map.put("name",item.getTitle());
                map.put("busstype",item.getBusstype());
                map.put("bussid",item.getBussid());
                map.put("userName",item.getNickName());
                map.put("seq",0);
                map.put("objpic",item.getObjpic());
                SysProcessBo param = new SysProcessBo();
                param.setBussid(item.getBussid());
                List<SysProcessVo> plist = processService.queryList(param);
                for(SysProcessVo vo : plist){
                    SysWorklogBo logParams = new SysWorklogBo();
                    logParams.setPid(vo.getPid());
                    List<SysWorklogVo> logs = worklogService.queryList(logParams);
                    vo.setLogs(logs);
                    if(vo.getStatus().equals("1")){
                        map.put("seq",vo.getSeq());
                    }
                    if(vo.getActime() != null){
                        vo.setActimeStr(DateUtil.format(vo.getActime(),"MM/dd HH:mm"));
                    }

                }
                map.put("items",plist);
                data.add(map);
            });
        }
        return R.ok(data);
    }
}
